import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import router from 'umi/router';
import { message } from 'antd';
import { fetchValidation } from '@/utils';
import {
  queryPostManagementDetail,
  queryGardenList,
  queryPosthouseTariff,
  operSaveOrUpdate,
  operDelete,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchGarden: Effect;
    fetchPosthouseTariff: Effect;
    saveOrUpdate: Effect;
    delete: Effect;
  };
  reducers: {
    save: Reducer;
    saveGaeden: Reducer;
    savePostTariff: Reducer;
    clear: Reducer;
  };
}

const stateInfo = {
  detailInfo: {},
  gardenInfo: {},
  postTariffList: [],
};

const Model: ModelType = {
  namespace: 'postManagementAdd',

  state: stateInfo,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryPostManagementDetail, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * fetchGarden({ payload }, { call, put }) {
      const response = yield call(queryGardenList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'saveGaeden',
        payload: response.body,
      });
    },

    * fetchPosthouseTariff({ payload }, { call, put }) {
      const response = yield call(queryPosthouseTariff, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'savePostTariff',
        payload: (data.body && data.body.list) || [],
      });
    },

    * saveOrUpdate({ payload }, { call, put }) {
      const response = yield call(operSaveOrUpdate, payload);
      const data = fetchValidation(response);
      if (data) {
        message.success(payload.id ? '修改成功' : '添加成功');
        yield put({
          type: 'global/setPath',
        });
        router.goBack();
      }
    },

    * delete({ payload: { state, ...query } }, { call, put }) {
      const response = yield call(operDelete, query);
      const data = fetchValidation(response);
      if (data) {
        message.success('删除成功');
        yield put({
          type: 'fetch',
          payload: { id: state },
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        detailInfo: action.payload,
      };
    },

    saveGaeden(state, action) {
      return {
        ...state,
        gardenInfo: action.payload,
      };
    },

    savePostTariff(state, { payload }) {
      return ({
        ...state,
        postTariffList: payload,
      });
    },

    clear() {
      return stateInfo;
    },
  },
};

export default Model;
